import ApiService from './apiService.js';

document.addEventListener('DOMContentLoaded', () => {
    const englishNameInput = document.getElementById('englishName');
    const generateBtn = document.getElementById('generateBtn');
    const resultsSection = document.getElementById('results');

    generateBtn.addEventListener('click', generateChineseNames);

    async function generateChineseNames() {
        const englishName = englishNameInput.value.trim();
        if (!englishName) {
            alert('Please enter your English name');
            return;
        }

        try {
            // Show loading state
            generateBtn.disabled = true;
            generateBtn.textContent = 'Generating...';
            resultsSection.innerHTML = '<div class="loading">Generating Chinese names...</div>';
            
            // Call API to generate names
            const response = await ApiService.generateChineseName(englishName);
            
            if (!response || !response.names || !response.names.length) {
                throw new Error('No names were generated');
            }
            
            displayResults(response.names);
        } catch (error) {
            console.error('Error:', error);
            resultsSection.innerHTML = `
                <div class="error-message">
                    Sorry, there was an error generating names. Please try again.
                    <br>
                    <small>Error details: ${error.message}</small>
                </div>
            `;
        } finally {
            // Reset button state
            generateBtn.disabled = false;
            generateBtn.textContent = 'Generate Names';
        }
    }

    function displayResults(nameOptions) {
        resultsSection.innerHTML = '';
        resultsSection.classList.add('active');

        nameOptions.forEach((option, index) => {
            const nameCard = document.createElement('div');
            nameCard.className = 'name-card';
            
            nameCard.innerHTML = `
                <h2>${option.chinese} (${option.pinyin})</h2>
                <dl class="name-details">
                    <dt>Character Meanings:</dt>
                    <dd>
                        ${Object.entries(option.characters).map(([char, meaning]) => 
                            `<strong>${char}</strong>: ${meaning}<br>`
                        ).join('')}
                    </dd>
                    
                    <dt>Cultural Significance:</dt>
                    <dd>${option.cultural}</dd>
                    
                    <dt>Personality Traits:</dt>
                    <dd>${option.personality}</dd>
                    
                    <dt>English Meaning:</dt>
                    <dd>${option.english_meaning}</dd>
                </dl>
            `;
            
            resultsSection.appendChild(nameCard);
        });
    }
});
